'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async uploadFile() {
    // /posts/:id	post
    // put 方式更新
    const { ctx } = this;
    const fs = require('fs');
    const path = require('path');
    //故名思意 异步二进制 写入流
    const awaitWriteStream = require('await-stream-ready').write;
    //管道读入一个虫洞。
    const sendToWormhole = require('stream-wormhole');

    const stream = await ctx.getFileStream();
    // 基础的目录
    const uplaodBasePath = 'app/public/uploads';
    // 生成文件名
    const filename = `${Date.now()}${Number.parseInt( Math.random() * 1000,)}${path.extname(stream.filename).toLocaleLowerCase()}`;
    const targetFile = path.join(uplaodBasePath, filename);
    // 写入流
    const writeStream = fs.createWriteStream(targetFile);
    let result;
    try {
      //异步把文件流 写入
      await awaitWriteStream(stream.pipe(writeStream));
      result = path.join('/public/uploads', filename);
    } catch (err) {
      //如果出现错误，关闭管道
      await sendToWormhole(stream);
    }

    ctx.set('Content-Type', 'application/json');
    if (!result) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: '参数不正确！' };
    } else {
      ctx.state = 200;
      ctx.body = { code: 200, data: result };
    }
  }

}

module.exports = HomeController;
